package com.tiantianyuegou.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.tiantianyuegou.activity.BaseActivity;
import com.tiantianyuegou.R;
import com.tiantianyuegou.adapter.RedPageAdapter;
import com.tiantianyuegou.app.SysApplication;
import com.tiantianyuegou.constant.Constant;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.http.SPHelper;
import com.tiantianyuegou.model.Ad;
import com.tiantianyuegou.model.TicketModel;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.TimeUtils;
import com.tiantianyuegou.util.ToastUtilsCenter;
import com.tiantianyuegou.util.Tools;
import com.tiantianyuegou.view.HorizontalListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static com.nostra13.universalimageloader.core.ImageLoader.*;
import static com.nostra13.universalimageloader.core.ImageLoader.getInstance;

/**
 * 商品详情
 * Created by huyang on 2016/1/8 0008.
 */
public class GoodsDetailActivity extends BaseActivity implements View.OnClickListener {
//     http://hjtech.wicp.net:8080/tiantianyuegou-api/product/detail?tgId=358&tmId=1216
//     http://www.zgttyg.com/tiantianyuegou-api/product/detail?tgId=342&tmId=130 商品详情
//    http://www.zgttyg.com/tiantianyuegou-api/car/add?tmId=130&tgId=342&count=1 加入购物车tmId=130& tgId=342& count=1 color size
//     http://www.zgttyg.com/tiantianyuegou-api/comment/list?tgId=1&page=1 商品评价
//     http://www.zgttyg.com/tiantianyuegou-api/collect/add?tmId=342&tgId=130 商品收藏
//    http://www.zgttyg.com/tiantianyuegou-api/collect/del?tmId=342&tgId=130 取消商品收藏

    //Activity activity;
    private List<Ad> adlist = new ArrayList<Ad>();
    private LinearLayout linearDot, goodsdetail_operation, lay_notuandetailgoods;
    private ImageView ADtips[];
    private int ADCurrentPage = 0;//当前页码
    private ViewPager adv_viewpage;
    private TextView tv_goods,tv_goods_jieshao,tv_jifendiyongmoney,tv_price, tv_saleprice, tv_salecount, tv_store, tv_redPacket, tv_deduction;
    private TextView tv_time, tv_content, tv_username, tv_rategrade, elvuate_none, tv_spec,evaluate_none;
    private TextView tv_freight,tv_goodsname,tv_pingjia_name,tv_pingjia_data;
    private ImageView iv_user, iv_collection,iv_evaluate;
    private TextView tv_shoppingcar, tv_collection, tv_buy, tv_share,tv_goods_sizes;
    private TextView tv_more_evluate, tv_title;
    private LinearLayout layout, layout_ticket, layout_collection;
    private RelativeLayout layout_evluate,rl_yonghupingjia,rl_product_detail;
 //   private WebView mWebView;
    private HorizontalListView mListView;
    private List<TicketModel> data;
    private RedPageAdapter mAdapter;
    private LoadingDialog loadingDialog;
    private String TAG = "GoodsDetailActivity";
    private String tgId;//商品id
    private String tmId;//会呀id
    private String tpPic;//商品图片
    private int mShopId;//店铺Id
    private String mShopName = "";//店铺名字
    private boolean isCollect = true;
    private Context context;
    private PopupWindow popupWindow;
    private UMImage image;
    private Double mGuanChange;
    private String mTpName;
    private String tpPrice;
    private String tpSalesCount;
    private String brief;
    private String color;
    private String size;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activtiy_goodsdetail);
       Tools.changeSystemBar(this);
        setTitle("商品详情");
        initViews();
        context = this;
        getCityIdByName();
        SysApplication.getInstance().addActivity(this);
        loadAdv();


    }

    @Override
    public void findViewByIds() {
        tv_goods_sizes = (TextView) findViewById(R.id.tv_goods_sizes);
        tv_goodsname = (TextView) findViewById(R.id.tv_goodsname);
        rl_product_detail = (RelativeLayout) findViewById(R.id.rl_product_detail);
        rl_yonghupingjia = (RelativeLayout) findViewById(R.id.rl_yonghupingjia);
        adv_viewpage = (ViewPager) findViewById(R.id.vp_adv);
        linearDot = (LinearLayout) findViewById(R.id.dot);
        layout = (LinearLayout) findViewById(R.id.layout);
        evaluate_none = (TextView) findViewById(R.id.evaluate_none);
        tv_jifendiyongmoney = (TextView) findViewById(R.id.tv_jifendiyongmoney);
        tv_goods_jieshao = (TextView) findViewById(R.id.tv_goods_jieshao);
        tv_price = (TextView) findViewById(R.id.tv_price);
        tv_salecount = (TextView) findViewById(R.id.tv_salecount);
        tv_saleprice = (TextView) findViewById(R.id.tv_saleprice);
        tv_store = (TextView) findViewById(R.id.tv_store);
//        加入购物车，
        tv_shoppingcar = (TextView) findViewById(R.id.tv_shopping_car);
//        立即购买
        tv_buy = (TextView) findViewById(R.id.tv_purchase);
        tv_collection = (TextView) findViewById(R.id.tv_collection);
        iv_collection = (ImageView) findViewById(R.id.iv_collecttion);
        tv_time = (TextView) findViewById(R.id.tv_time);
        tv_username = (TextView) findViewById(R.id.tv_username);
        tv_content = (TextView) findViewById(R.id.tv_content);
        tv_rategrade = (TextView) findViewById(R.id.tv_rategrade);
        iv_user = (ImageView) findViewById(R.id.iv_user);
        iv_evaluate = (ImageView) findViewById(R.id.iv_haoping);
        layout_collection = (LinearLayout) findViewById(R.id.layout_collection);
        elvuate_none = (TextView) findViewById(R.id.evaluate_none);
        tv_spec = (TextView) findViewById(R.id.tv_spec);
        tv_title = (TextView) findViewById(R.id.tv_title);
        layout_evluate = (RelativeLayout) findViewById(R.id.layout_evaluate);
        goodsdetail_operation = (LinearLayout) findViewById(R.id.goodsdetail_operation);
        lay_notuandetailgoods = (LinearLayout) findViewById(R.id.lay_notuandetailgoods);

    }

    @Override
    public void initListener() {
        data = new ArrayList<>();
        mAdapter = new RedPageAdapter(this);
        loadingDialog = new LoadingDialog(this);
        //设置删除线
//        tv_price.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        rl_yonghupingjia.setOnClickListener(this);
        tv_shoppingcar.setOnClickListener(this);
        tv_buy.setOnClickListener(this);

        layout_collection.setOnClickListener(this);
        layout.setOnClickListener(this);
        rl_product_detail.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    //商品详情
    @Override
    public void initData() {

        Intent intent = getIntent();
        tgId = intent.getStringExtra("tgId");
        tmId = intent.getStringExtra("tmId");
        Log.e(TAG, "获取到传递的数据是" + tgId + "==============" + tmId + "6262626262");
        String type = intent.getStringExtra("type");
        System.out.println("------------type=" + type);
        if (type != null) {
            if (type.equals("MyCollectionActivity")) {
//                获取到商品id与会员id
                tgId = intent.getStringExtra("tgId");
                tmId = intent.getStringExtra("tmId");


                Log.e(TAG, "获取到传递的数据是" + tgId + "==============" + tmId + "1111111111");
                tv_collection.setText("已收藏");
                tv_collection.setTextColor(getResources().getColor(R.color.red));
                iv_collection.setImageResource(R.mipmap.already_collect);
                isCollect = false;
                if (isCollect) {
                    tv_collection.setText("收藏");
                    tv_collection.setTextColor(getResources().getColor(R.color.black));
                    iv_collection.setImageResource(R.mipmap.not_collect);
                    isCollect = true;
                    cancelCollect();
                }
            } else if (type.equals("CategoryFragment") || type.equals("TuangouStoreDetailActivity")) {
                tgId = intent.getStringExtra("tgId");
                tpPic = intent.getStringExtra("tmId");
            }
        } else {
//            获取商品id与会员id
            tgId = intent.getStringExtra("tgId");
            tmId = intent.getStringExtra("tmId");
            Log.e(TAG, "获取到传递的数据是" + tgId + "==============" + tmId + "58585858558");
        }
        loadingDialog.showDialog();
        loadingDialog.setMsg("正在加载");
        RequestParams params = new RequestParams();
        params.addBodyParameter("tgId",  tgId);
        String tmId = SPHelper.getTmId();
        Log.e("TAG", "tmId:" + tmId);
        if (tmId != null && !"".equals(tmId)) {
            params.addBodyParameter("tmId", tmId);
        } else {
            params.addBodyParameter("tmId", tmId);
        }
        Log.e(TAG, "tpid=" + tgId);
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.GOODS_DETAIL, params, new RequestCallBack<String>() {


            @Override
            public void onSuccess(ResponseInfo<String> response) {
                loadingDialog.dismiss();
                iv_collection.setEnabled(true);
                tv_buy.setEnabled(true);
                tv_collection.setEnabled(true);
                tv_shoppingcar.setEnabled(true);
                Log.e(TAG, "onSuccess response.result  "
                        + response.result);

                if (TextUtils.isEmpty(response.result)) {
                    showMsg("获取商品详情失败");
                    iv_collection.setEnabled(false);
                    tv_buy.setEnabled(false);
                    tv_collection.setEnabled(false);
                    tv_shoppingcar.setEnabled(false);
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(response.result);
                        String code = jsonObject.getString("code");
                        String tmId = SPHelper.getTmId();
                        Log.e("TAG", "tmId:" + tmId);
                       /* if (tmId != null && !"".equals(tmId)) {
                            String collected = jsonObject.getString("tg_sales_volume");
                            if (collected.equals("1")) {
                                tv_collection.setText("已收藏");
                                tv_collection.setTextColor(getResources().getColor(R.color.red));
                                iv_collection.setImageResource(R.mipmap.already_collect);
                                isCollect = false;
                                //addCollect();
                            } else if (collected.equals("0")) {
                                tv_collection.setText("收藏");
                                tv_collection.setTextColor(getResources().getColor(R.color.black));
                                iv_collection.setImageResource(R.mipmap.not_collect);
                                isCollect = true;
                                cancelCollect();
                            }
                        }*/
//                        mGuanChange = 1 / jsonObject.getDouble("guanchange");
                        if (code.equalsIgnoreCase("100")) {
//                            获取商品详情进行显示数据并修改页显示数据
                          /*  tg_id：商品id
                            tg_name：商品名称
                            tg_number：商品编号
                            tg_price：价格
                            tg_grand：品牌
                            tg_model：型号
                            tg_color：颜色(多个逗号隔开)
                            tg_size：尺寸(多个逗号隔开)
                            tg_brief：详情
                            tg_count：库存
                            tg_sales_volume：销量
                            integral：抵用积分
                            isColect：是否已收藏(0:否 1:是)*/
                            JSONObject json = jsonObject.getJSONObject("list");
//                            需要产品名称，价格，积分抵用，累计销售，库存，颜色，尺码，详情，评价（头像，名称，日期，内容）
                            String tpName = json.getString("tg_name");
                            mTpName = tpName;
                             tpPrice = json.getString("tg_price");//商品价格
                            String tpIntegral = json.getString("integral");//积分
//                            String tpSalePrice = json.getString("tpSalePrice");
                            String tpVolume = json.getString("tg_sales_volume");//销量
                            tpSalesCount = json.getString("tg_count");//库存
                           color = json.getString("tg_color");//颜色
                             size = json.getString("tg_size");//尺寸
                            brief = json.getString("tg_brief");
                            evaluate_none.setVisibility(View.GONE);
                            tv_saleprice.setText("￥"+tpPrice);
                            tv_jifendiyongmoney.setText(tpIntegral);
                            tv_salecount.setText(tpSalesCount);
                            tv_store.setText(tpSalesCount);
                            tv_goodsname.setText(tpName);

//                            tv_goods.setText(color);
//                            tv_goods_sizes.setText(size);
//
                            Log.e(TAG, "商品详情数据是======="+tpName + tpPrice + tpIntegral  + tpVolume + tpSalesCount + color + size + brief);
                            if (color.contains(",")){
                                String[] colors = color.split(",");
                                for (int i = 0; i < colors.length; i++) {
                                    String photo = color.substring(0, color.indexOf(","));
                                    //shareImg = photo;
                                    Ad ad = new Ad(photo);
                                    adlist.add(ad);
                                }
                            }
                        } else if (code.equalsIgnoreCase("103")) {

                            goodsdetail_operation.setVisibility(View.GONE);
                            lay_notuandetailgoods.setVisibility(View.GONE);
                            iv_collection.setEnabled(false);
                           tv_buy.setEnabled(false);
                            tv_collection.setEnabled(false);
                           tv_shoppingcar.setEnabled(false);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        iv_collection.setEnabled(false);
                    //+    tv_buy.setEnabled(false);
                        tv_collection.setEnabled(false);
                 //+       tv_shoppingcar.setEnabled(false);
                    }
                }
            }



            @Override
            public void onFailure(HttpException e, String s) {
                loadingDialog.dismiss();
//                showMsg("当前网络不可用，请检查网络设置");
                iv_collection.setEnabled(false);
                tv_buy.setEnabled(false);
                tv_collection.setEnabled(false);
           //+     tv_shoppingcar.setEnabled(false);
            }
        });
    }

    //根据城市名称获取城市id
    private void getCityIdByName() {
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("name", Constant.cName);
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.FIND_LOCATION_BY_NAME, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("TAG", "get cityIdByName response:" + responseInfo.result);
                if (TextUtils.isEmpty(responseInfo.result)) {
                    showMsg("没有该城市的Id");
                } else {
                    try {
                        JSONObject root = new JSONObject(responseInfo.result);
                        String code = root.getString("code");
                        if ("100".equals(code)) {
                            JSONObject result = root.getJSONObject("result");
                            int id = result.getInt("id");
//                            getFreight(id);
                        } else {
//                            String msg = root.getString("message" );
//                            showMsg(msg);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        showMsg("解析异常");
                    }
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {
                Log.e("TAG", "get cityIdByName failure :" + s);
//                showMsg("当前网络不可用,请检查您的网络设置");
            }
        });
    }
//     http://www.zgttyg.com/tiantianyuegou-api/comment/list?tgId=342&page=1 商品评价
//     http://www.zgttyg.com/tiantianyuegou-api/collect/add?tmId=342&tgId=130 商品收藏
//    http://www.zgttyg.com/tiantianyuegou-api/collect/del?tmId=342&tgId=130 取消商品收藏

    //用户评价
    public void userEveluate() {
        RequestParams params11 = new RequestParams();
        params11.addBodyParameter("tgId", tgId);
        params11.addBodyParameter("page", "1");
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.PINGJIA, params11, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> response) {
                Log.v(TAG, "onSuccess response.result  "
                        + response.result);
                if (TextUtils.isEmpty(response.result)) {
                    showMsg("评论获取失败");
                    layout.setEnabled(false);
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(response.result);
                        String code = jsonObject.getString("code");
                        if (code.equalsIgnoreCase("100")) {
                            JSONArray list = jsonObject.getJSONArray("list");
//                            message：请求结果描述
//                            tm_name：评价人
//                            tgsd_evaluate：评价内容
//                            tgsd_star：评价星级
//                            tgsd_add_date：评价时间
                            if (list.length() > 0) {
                                JSONObject temp = list.getJSONObject(0);
                                String tmName = temp.getString("tm_name");
                                String tmAvatar = temp.getString("tgsd_evaluate");
                                String tcContent = temp.getString("tcContent");
                                String tcAddtiem = temp.getString("tgsd_star");
                                String tcRateGtade = temp.getString("tgsd_add_date");
                                System.out.println("-----------tcContent" + tcContent + "--------");
                                evaluate_none.setVisibility(View.GONE);
                                iv_user.setVisibility(View.VISIBLE);
                                tv_username.setText(tmName);

                                tv_time.setText(TimeUtils.convertTimeYMD(Long.valueOf(tcAddtiem)));
                                getInstance().displayImage(tmAvatar, iv_user);
                                if ("1".equals(tcRateGtade)) {
                                    tv_rategrade.setText("差评");
                                    iv_evaluate.setImageResource(R.mipmap.chaping);
                                } else if ("2".equals(tcRateGtade)) {
                                    tv_rategrade.setText("中评");
                                    iv_evaluate.setImageResource(R.mipmap.zhongping);
                                } else if ("3".equals(tcRateGtade)) {
                                    tv_rategrade.setText("好评");
                                    iv_evaluate.setImageResource(R.mipmap.haoping);
                                }
                                tv_pingjia_name.setText(tmName);
                                tv_pingjia_data.setText(TimeUtils.convertTimeYMD(Long.valueOf(tcAddtiem)));
                                tv_goods.setText(color);
                                tv_goods_sizes.setText(size);
                                tv_content.setText(tcContent);
                            }

                        } else {
//                            showMsg("商品数据为空");
//                            goodsdetail_operation.setVisibility(View.GONE);
//                            lay_notuandetailgoods.setVisibility(View.GONE);

                            layout_evluate.setVisibility(View.GONE);
                            tv_title.setVisibility(View.GONE);
                            elvuate_none.setVisibility(View.VISIBLE);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();

                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

//                showMsg("当前网络不可用，请检查网络设置");
            }
        });

    }

   /* //商品轮播图
    public void changeAdv() {
        ADtips = new ImageView[adlist.size()];
        for (int i = 0; i < ADtips.length; i++) {
            ImageView img = new ImageView(this);
            LinearLayout.LayoutParams layoutParam = new LinearLayout.LayoutParams(20, 20);
            ADtips[i] = img;
            if (i != 0) {
                layoutParam.leftMargin = 5;
                img.setBackgroundResource(R.mipmap.homead_nochoose);//黑色背景
            } else {
                img.setBackgroundResource(R.mipmap.homead_choose);// 蓝色背景
            }
            linearDot.addView(img, layoutParam);
        }
        // 通过适配器引入图片
        MyViewPager mAdapter = new MyViewPager(this, adlist);
        Log.e(TAG, "adlist:" + adlist.size());
//        TODO 添加真正的网络请求轮播图地址
//        adv_viewpage.setAdapter(mAdapter);
        adv_viewpage.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                ADtips[ADCurrentPage]
                        .setBackgroundResource(R.mipmap.homead_nochoose);
                ADCurrentPage = position;
                ADtips[position]
                        .setBackgroundResource(R.mipmap.homead_choose);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        // 计时器
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                GoodsDetailActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ADtips[ADCurrentPage]
                                .setBackgroundResource(R.mipmap.homead_nochoose);
                        if (ADCurrentPage == ADtips.length - 1) {
                            ADCurrentPage = 0;
                        } else {
                            ADCurrentPage++;
                        }
                        ADtips[ADCurrentPage]
                                .setBackgroundResource(R.mipmap.homead_choose);
                        adv_viewpage
                                .setCurrentItem(ADCurrentPage);
                    }
                });
            }
        }, 5000, 5000);//轮播结束
    }*/


    /**
     * 加载轮播图
     */
    public void loadAdv() {

        RequestParams params = new RequestParams();
        params.addBodyParameter("tacCataId", 1+"");
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.HOME_ADV_LIST, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> response) {
                Log.e(TAG, "onSuccess response.result" +
                        response.result);
                if (TextUtils.isEmpty(response.result)) {
                    showMsg("加载轮播图失败");
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(response.result);
                        String code = jsonObject.getString("code");
                        if (code.equalsIgnoreCase("100")) {
                            JSONArray result = jsonObject.getJSONArray("list");
                            if (result.length() > 0) {
                                adlist.clear();
                                for (int i = 0; i < result.length(); i++) {
                                    JSONObject temp = result.getJSONObject(i);
                                    String tacId = temp.getString("tacId");
                                    String tacPhoneImage = temp.getString("tacPhoneImage");
                                    String tacLink = temp.getString("tacLink");

                                    Ad adImage = new Ad(tacId, tacPhoneImage, tacLink);
                                    adlist.add(adImage);

                                }
                                changeAdv();
                                Log.e(TAG, adlist.size() + "sadsadasd");
                            }

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });

    }

    public void changeAdv() {
        ADtips = new ImageView[adlist.size()];
        for (int i = 0; i < ADtips.length; i++) {
            ImageView img = new ImageView(GoodsDetailActivity.this);
            LinearLayout.LayoutParams layoutParam = new LinearLayout.LayoutParams(20, 20);
            ADtips[i] = img;
            if (i != 0) {
                layoutParam.leftMargin = 5;
                img.setBackgroundResource(R.mipmap.homead_nochoose);//黑色背景
            } else {
                img.setBackgroundResource(R.mipmap.homead_choose);// 蓝色背景
            }
            linearDot.addView(img, layoutParam);
        }
        // 通过适配器引入图片
        MyViewPager mAdapter = new MyViewPager(GoodsDetailActivity.this, adlist);
        adv_viewpage.setAdapter(mAdapter);
        adv_viewpage.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                ADtips[ADCurrentPage]
                        .setBackgroundResource(R.mipmap.homead_nochoose);
                ADCurrentPage = position;
                ADtips[position]
                        .setBackgroundResource(R.mipmap.homead_choose);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        // 计时器
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ADtips[ADCurrentPage]
                                .setBackgroundResource(R.mipmap.homead_nochoose);
                        if (ADCurrentPage == ADtips.length - 1) {
                            ADCurrentPage = 0;
                        } else {
                            ADCurrentPage++;
                        }
                        ADtips[ADCurrentPage]
                                .setBackgroundResource(R.mipmap.homead_choose);
                        adv_viewpage
                                .setCurrentItem(ADCurrentPage);
                    }
                });
            }
        }, 5000, 5000);
        // 轮播图结束
    }


    //    图片数组
    String[] imageViews = { "http://www.zgttyg.com/tiantianyuegou-gm/upload/project/20160912173803_0.jpg", "http://www.zgttyg.com/tiantianyuegou-gm/upload/project/20160905120000_3.jpg",
            " http://www.zgttyg.com/tiantianyuegou-gm/upload/project/20160905115937_0.jpg"};
    BitmapUtils bitmapUtils;
    class MyViewPager extends PagerAdapter{
        private Context context;
        private List<Ad> data = new ArrayList<>();

        public MyViewPager(Context context, List<Ad> data) {
            this.context = context;
            this.data = data;
             bitmapUtils = new BitmapUtils(GoodsDetailActivity.this);
        }

        @Override
        public int getCount() {
            return imageViews.length;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
//            将view添加到container中并将view给返回
            View view = View.inflate(GoodsDetailActivity.this, R.layout.adapter, null);
            ImageView imageView = (ImageView) view.findViewById(R.id.img);
            bitmapUtils.display(imageView,imageViews[position]);
//            将请求到的图片添加到viewpager中
//            ImageLoader.getInstance().displayImage(imageViews[position], imageView);
            Log.e("图片的地址是========",imageViews[position]);
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
//            super.destroyItem(container, position, object);
            container.removeView((View) object);
        }
    }

    //添加收藏
    private void addCollect() {

        String tmId = SPHelper.getTmId();

        System.out.println("---------" + tmId + "------" + tgId);
        RequestParams params = new RequestParams();
//        params.addBodyParameter("tmId",tmId);
//        params.addBodyParameter("tgId",tgId);
        params.addBodyParameter("tmId", 1216+"");
        params.addBodyParameter("tgId", tgId);
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.ADD_COLLECT, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> response) {
                Log.e(TAG, "onSuccess response.result" +
                        response.result);
                if (TextUtils.isEmpty(response.result)) {
                  ToastUtilsCenter.makeText(context, "抱歉，收藏失败", false).show();
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(response.result);
                        String code = jsonObject.getString("code");
                        if (code.equalsIgnoreCase("100")) {
                          ToastUtilsCenter.makeText(context, "收藏成功", true).show();
                        } else if (code.equalsIgnoreCase("101")) {
                           ToastUtilsCenter.makeText(context, "抱歉，收藏失败", false).show();
                        } else if (code.equalsIgnoreCase("103")) {
                           ToastUtilsCenter.makeText(context, "会员不存在", false).show();
                        }else if (code.equalsIgnoreCase("104")){
                            ToastUtilsCenter.makeText(context, "商品不存在", false).show();

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

                showMsg("当前网络不可用，请检查网络设置");
            }
        });
    }

    //取消收藏
    private void cancelCollect() {

        String tmId = SPHelper.getTmId();

        RequestParams params = new RequestParams();
        params.addBodyParameter("tmId", 1216+"");
        params.addBodyParameter("tgId", tgId);
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.DELTE_COLLECT, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> response) {
                Log.e(TAG, "onSuccess response.result" +
                        response.result);
                if (TextUtils.isEmpty(response.result)) {
                    ToastUtilsCenter.makeText(context, "抱歉，取消收藏失败", false).show();
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(response.result);
                        String code = jsonObject.getString("code");
                        if (code.equalsIgnoreCase("100")) {
                          ToastUtilsCenter.makeText(context, "取消收藏成功", true).show();
                        } else if (code.equalsIgnoreCase("101")) {
                           ToastUtilsCenter.makeText(context, "抱歉，取消收藏失败", false).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

                showMsg("当前网络不可用，请检查网络设置");
            }
        });

    }

    @Override
    public void onClick(View view) {
        //UMImage image = new UMImage(GoodsDetailActivity.this, "http://www.umeng.com/images/pic/social/integrated_3.png" );

        switch (view.getId()) {
            case R.id.tv_shopping_car:
                if ("".equals(SPHelper.getTmId())) {
//                    if ("".equals("")){
                    Log.e("获取到的商品id是", "请求到的数据是===========" + SPHelper.getTmId() + "==============");
                    Intent intent = new Intent(this, LoginActivity.class);
                    intent.putExtra("type","GoodsDetailActivity");
                    startActivityForResult(intent, 1001);
                } else {
                    Log.e("获取到的商品id是", "请求到的数据是===========" + SPHelper.getTmId() + "==============");
                    Intent intent = new Intent(GoodsDetailActivity.this, BuyOrAddActivity.class);
                    intent.putExtra("type", "shoppingCar");
                    intent.putExtra("tmId", 1216);
                    intent.putExtra("tgId", tgId);
                    intent.putExtra("count", tpSalesCount);
//                    intent.putExtra("color", );
//                    intent.putExtra("size", );
                    intent.putExtra("price", tpPrice);
                    intent.putExtra("shopName", mShopName);
                    intent.putExtra("productName", tv_goodsname.getText().toString());
                    intent.putExtra("productPic", tpPic);
//                    intent.putExtra("productRedPacket", tv_redPacket.getText().toString());
//                    Double guanPrice = Double.valueOf(tv_deduction.getText().toString().substring(1));
//                    intent.putExtra("canUseGuan", new DecimalFormat("0").format(guanPrice / mGuanChange));
//                    intent.putExtra("unitPrice", new DecimalFormat("0.00").format(mGuanChange));
                    startActivityForResult(intent, Constant.ADD_SHOPPING_CAR_REQUEST);
                }
                break;
            case R.id.tv_purchase:
                Intent intent6 = new Intent(GoodsDetailActivity.this, BuyOrAddActivity.class);
             startActivity(intent6);

                if ("".equals(SPHelper.getTmId())) {
                    Intent intent = new Intent(this, LoginActivity.class);
                    intent.putExtra("type","GoodsDetailActivity");
                    startActivityForResult(intent, 1002);
                } else {
                    Intent intent1 = new Intent(GoodsDetailActivity.this, BuyOrAddActivity.class);
                    intent1.putExtra("type", "buy");
                    intent1.putExtra("tmId", 1216);
                    intent1.putExtra("tgId", tgId);
//                    intent1.putExtra("color", );
//                    intent1.putExtra("size", );
                    intent1.putExtra("count", 1);
                    intent1.putExtra("shopName", mShopName);
                    intent1.putExtra("productName", tv_goodsname.getText().toString());
                    intent1.putExtra("productPic", tpPic);
                    Log.e("TAG", "pic:" + tpPic);
//                    Double guanPrice = Double.valueOf(tv_deduction.getText().toString().substring(1));
//                    intent1.putExtra("canUseGuan", new DecimalFormat("0").format(guanPrice / mGuanChange));
//                    intent1.putExtra("unitPrice", new DecimalFormat("0.00").format(mGuanChange));
//                    intent1.putExtra("productRedPacket", tv_redPacket.getText().toString());
                    startActivity(intent1);
                }
                break;
            case R.id.layout_collection:
                if ("".equals(SPHelper.getTmId())) {
                    Intent intent = new Intent(this, LoginActivity.class);
                    intent.putExtra("type","GoodsDetailActivity");
                    startActivityForResult(intent, 1003);
                } else {
                    if (isCollect) {
                        tv_collection.setText("已收藏");
                        tv_collection.setTextColor(getResources().getColor(R.color.red));
                        iv_collection.setImageResource(R.mipmap.already_collect);
                        isCollect = false;
                        addCollect();
                    } else {
                        tv_collection.setText("收藏");
                        tv_collection.setTextColor(getResources().getColor(R.color.black));
                        iv_collection.setImageResource(R.mipmap.not_collect);
                        isCollect = true;
                        cancelCollect();
                    }
                }
                break;
            case R.id.layout:
//                跳转到用户评价界面
                Intent intent = new Intent(GoodsDetailActivity.this, YongHuPingJiaActivity.class);
//             传递商品id用户评价界面根据商品id及你想那个网络请求获取数据并展示数据
                intent.putExtra("tgId", tgId);
                startActivity(intent);
            break;
            case R.id.rl_product_detail:
                //跳转到产品详情
                Intent proder = new Intent(GoodsDetailActivity.this,ProductDetailActivity.class);
                proder.putExtra("brief",brief);
                startActivity(proder);

                break;
            default:
                break;
        }
    }




   /* class MyViewPager extends PagerAdapter {

        private Context context;
        private List<Ad> data = new ArrayList<>();

        public MyViewPager(Context context, List<Ad> data) {
            this.context = context;
            this.data = data;
        }

        @Override
        public int getCount() {
            return data.size();
        }

        *//**
         * true表示无需创建 false表示需要创建
         *//*
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        *//**
         * 设置view多个界面
         *//*
        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            Ad adImage = adlist.get(position % adlist.size());
            View view = View.inflate(GoodsDetailActivity.this, R.layout.adapter, null);
            ImageView img = (ImageView) view.findViewById(R.id.image);
            getInstance().displayImage(adImage.getTacPhoneImage(), img);
            container.addView(view);
            return view;
        }

        *//**
         * 销毁page position:当前要销毁第几个page object：当前需要销毁的page
         *//*
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            // super.destroyItem(container, position, object);
            container.removeView((View) object);
        }
    }
*/

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /** attention to this below ,must add this**/
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.ADD_SHOPPING_CAR_REQUEST) {
            if (resultCode == Constant.ADD_SHOPPING_CAR_RESULT) {
                ToastUtilsCenter.makeText(this, "加入购物车成功", true).show();
            }
        }
    }

}
